package pers.vic.system.system.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pers.vic.base.bo.system.SysDict;
import pers.vic.base.pager.Lookup;
import pers.vic.base.pager.PageInfo;
import pers.vic.base.service.BaseService;
import pers.vic.system.system.mapper.SysDictMapper;

/**
 * 数据字典表 Service
 * 
 * @author VIC
 */
@Service
public class SysDictService extends BaseService {

	@Resource
	private SysDictMapper sysDictMapper;

	/**
	 * 查询列表
	 */
	public PageInfo<SysDict> list(Lookup lookup) {
		startPage(lookup);
		List<SysDict> datas = sysDictMapper.list(lookup);
		return PageInfo.instance(datas, lookup);
	}

	/**
	 * 根据主键查询
	 */
	public SysDict findById(int id) {
		return sysDictMapper.findById(id);
	}
	

	/**
	 * 根据主键数组查询
	 */
	public List<SysDict> findByIds(int... ids) {
		return sysDictMapper.findByIds(ids);
	}

	/**
	 * 新增
	 * code需要根据pcode手动生成
	 */
	@Transactional
	public int insert(SysDict entity) {
		Long pcode = entity.getPcode();
		Long code = getMaxChildCode(pcode);
		entity.setCode(code +1);//超出范围了 会报错  此处不处理
		return sysDictMapper.insert(entity);
	}
	


	/**
	 * 修改
	 */
	@Transactional
	public int update(SysDict entity) {
		return sysDictMapper.update(entity);
	}

	/***
	 * 删除
	 */
	@Transactional
	public int delete(int... ids) {
		return sysDictMapper.delete(ids);
	}

	/* ****************************************************************/
	/**
	 * 获取所有子节点
	 * 
	 * @param code
	 * @return
	 */
	public List<SysDict> findAllChildDict(Long code) {
		long codeL = code.longValue();
		long limitMax = 0;
		long limitMin = 0;
		if(code == 0) {//查询根节点
			limitMax = 2;
			limitMin = 0;		
		}else if(code ==1) {
			limitMax = (codeL + 1) * 100;
			limitMin = codeL * 100;
		}else {
			limitMax = (codeL + 1) * 1000;
			limitMin = codeL * 1000;
		}
		return sysDictMapper.findAllChildDict(limitMin, limitMax);
	}
	
	/**根据code查询*/
	public SysDict findByCode(long code) {
		return sysDictMapper.findByCode(code);
	}

	/**逻辑删除*/
	public void mockDelete(Long code) {
		sysDictMapper.mockDelete(code);
		
	}
	
	private Long getMaxChildCode(Long pcode) {
		long codeL = pcode.longValue();
		long limitMax = 0;
		long limitMin = 0;
		if (pcode == 1) {
			limitMax = (codeL + 1) * 100;
			limitMin = codeL * 100;
		} else {
			limitMax = (codeL + 1) * 1000;
			limitMin = codeL * 1000;
		}
		Long maxChildCode=sysDictMapper.getMaxChildCode(limitMax, limitMin);
		if(maxChildCode==null){
			maxChildCode=limitMin;
		}
	return maxChildCode;
	}
}
